<template>
  <div class="chat-content-wrap">
    <div class="history-wrap">
      <!--正在对话-->
      <div v-if="chatHistory.length">
        <!--ai回答-->
        <div v-for="(item,idx) in chatHistory">
          <!--用户输入相关文字-->
          <div class="right-person" v-if="item.msgType == '3'">
            <div class="left-info wenzi">
              <div class="bubble" :class="fullScreen ? 'bubble-full' : ''">
                <div class="title">{{ item.content }}</div>
              </div>
            </div>
          </div>
          <!--ai回答-->
          <div>
            <div class="left-person" v-if="item.msgType == '100' && !item.show">
              <div class="left-img">
                <img src="../../assets/image/aichat/aiRobot.png">
              </div>
              <div class="right-info">
                <div class="bubble" :class="fullScreen ? 'bubble-full' : ''">
                  <div class="content-text" v-if="submitFlag && idx==chatHistory.length-1 && printedText"
                       v-html="renderedMarkdown(printedText, true)"></div>
                  <div class="show-chat" v-else>
                    <img style="width: 20px; height: 20px;" src="../../assets/image/common/load.gif"/>
                    <span class="show-chat-tip" v-for="(text,index) in showChatTip"
                          :style="'--i:' + (index+1)">{{ text }}</span>
                  </div>
                </div>
              </div>
            </div>
            <!--回答完毕显示卡片-->
            <div v-if="item.show">
              <div class="left-person">
                <div class="left-img">
                  <img src="../../assets/image/aichat/aiRobot.png">
                </div>
                <!--加载中-->
                <div class="right-info">
                  <div class="text-bold">制度检索小助手</div>
                </div>
              </div>
              <!--加载完毕-->
              <div class="ai-reply">
                <!--ai回复盒子-->
                <div class="padding-left-sm padding-right-sm text-171717">
                  <div>
                    <div class="header-box flex align-center">
                      <img width="27" height="27" src="../../assets/image/aichat/title-icon.png"/>
                      <div class="text">检索结果总结</div>
                    </div>
                    <div class="padding-left">
                      <el-row class="padding-top-sm ">
                        <el-col :span="8">
                          涉及地市：{{ details.result1?.citys.length ? details.result1.citys.join('、') : '' }}
                          <!--                        <span v-html="parseText(item.content).summary.source"></span>-->
                        </el-col>
                        <el-col :span="8">
                          发布时间：{{ details.result1?.times }}
                          <!--                        <span v-html="parseText(item.content).summary.releaseTime"></span>-->
                        </el-col>
                      </el-row>
                      <el-row class="padding-top-sm">
                        <el-col :span="16">
                          涉及文件数：{{ details.result1?.files }}
                          <!--                        <span v-html="parseText(item.content).summary.count"></span>-->
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                  <div>
                    <div class="flex padding-top-xl align-center padding-left">
                      <img  width="27" height="27" src="../../assets/image/aichat/title-icon.png"/>
                      <div class="text">对比情况</div>
                    </div>
                    <div class="padding-top-sm padding-left">
                      {{ details.result2?.between }}
                    </div>
                  </div>
                  <div class="padding-top-sm padding-bottom-sm min-height padding-left padding-right" v-loading="loading3">
                    <div class="text-232323 text-bold padding-top-sm">目标原文</div>
                    <div class="padding-sm margin-top bg-F0F7FF relative"
                         v-for="(item2,index) in details.result3?.original">
                      <div>
                        <div v-html="item2.content"></div>
                      </div>
                      <div class="absolute bg-white text-blue text-center padding-top-xs padding-bottom-xs">
                        <el-popover
                            placement="bottom-end"
                            :width="450"
                            trigger="hover"
                        >
                          <el-row>
                            <el-col :span="24" class="text-bold">{{ item2.filename }}</el-col>
                            <el-col class="padding-top-4" :span="12">{{item2.city}} {{item2.department}}</el-col>
                            <el-col class="padding-top-4" :span="12">发布时间：{{item2.time}}</el-col>
                            <!--                            <el-col class="padding-top-4" :span="24">联系人：<a class="text-blue">王成-->
                            <!--                              wangcheng@cmccjs.com</a></el-col>-->
                          </el-row>
                          <template #reference>
                            <div class="pointer">
                              <span class="iconfont lianjie1"></span>来源
                            </div>
                          </template>
                        </el-popover>
                      </div>
                    </div>
                  </div>

                </div>
                <div class="right-img"></div>
              </div>
            </div>
          </div>
        </div>
        <!--正在加载ai回答-->
        <div class="left-person" v-if="showChatLoading">
          <div class="left-img">
            <img src="../../assets/image/aichat/aiRobot.png">
          </div>
          <div class="right-info">
            <div class="bubble" :class="fullScreen ? 'bubble-full' : ''">
              <div class="show-chat">
                <img style="width: 20px; height: 20px;" src="../../assets/image/common/load.gif"/>
                <span class="show-chat-tip" v-for="(text,index) in showChatTip"
                      :style="'--i:' + (index+1)">{{ text }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--没有过对话-->
      <div v-else class="no-chat">
        <div>
          <div class="text">
            <span class="text-24">您好</span>
            <span>
                  , 我是您的制度检索Al小助手
                </span>
          </div>
          <div class="text-3E3E3E padding-top-xs text-sm">
            汇集移动内部全量制度，支持按地市、部门检索制度，可对不同地市不同部门的制度内容进行比较
          </div>
          <el-row class="padding-tb-xl">
            <el-col :span="20">
              <ul class="grid col-3">
                <li>
                  <div class="margin-xs tip-item item1 text-center flex align-center">
                    <img src="../../assets/image/aichat/tip-icon1.png">
                    <div class="padding-left"> 搜索对应地市制度</div>
                  </div>
                </li>
                <li>
                  <div class="margin-xs tip-item item2 text-center flex align-center">
                    <img src="../../assets/image/aichat/tip-icon2.png">
                    <div class="padding-left"> 搜索对应部门制度</div>
                  </div>
                </li>
                <li>
                  <div class="margin-xs tip-item item3 text-center flex align-center">
                    <img src="../../assets/image/aichat/tip-icon3.png">
                    <div class="padding-left"> 比较不同地市制度</div>

                  </div>
                </li>
              </ul>
            </el-col>
          </el-row>
          <el-row class="">
            <el-col :span="18">
              <ul class="grid col-3 text-sm">
                <li @click="tipClick(0)" class="pointer">
                  <div class="margin-xs tip2-item bg-white text-center flex align-center">
                    <div class="padding-left"> 搜索常州的号卡管理制度</div>
                  </div>
                </li>
                <li @click="tipClick(1)" class="pointer">
                  <div class="margin-xs tip2-item bg-white  text-center flex align-center">
                    <div class="padding-left"> 帮我比较常州和盐城商机管理制度</div>
                  </div>
                </li>
                <li @click="tipClick(2)" class="pointer">
                  <div class="margin-xs  tip2-item bg-white text-center flex align-center">
                    <div class="padding-left"> 搜索省公司和盐城的商机更新制度</div>
                  </div>
                </li>
              </ul>
            </el-col>
          </el-row>
        </div>
        <div class="right-img"></div>
      </div>


    </div>
  </div>
</template>

<script setup>
import {defineEmits, defineExpose, defineProps, getCurrentInstance, nextTick, onMounted, ref, watch} from 'vue'
//引入相关样式
import '@vue-office/docx/lib/index.css'
import {removeLastHash} from "@/utils/index.js";


let props = defineProps(['chatHistory', 'showChatLoading', 'showChatTip', 'submitFlag', '', 'fullScreen']);
let emit = defineEmits(['resetIndexData', 'submitLeadInfo', 'submitOrder', 'submitCode', 'submitRate',
  'viewProductDetail', 'submitMeOrder', 'viewSolutionDetail', 'unsubscribeOrder', 'resetSubmit', 'resetScroll',
  'queryProductIdList', 'queryRateIdList', 'querySolutionIdList', 'queryOrderList', 'querySubscriptionList', 'queryBillDetailList',
  'addStreamToIndexDB']);

const {proxy} = getCurrentInstance()

// 聊天记录list
const chatHistory = ref([])


watch(() => props.chatHistory, () => {
  chatHistory.value = props.chatHistory
  nextTick(() => {
    const aTags = document.querySelectorAll('a');

    // 遍历所有的 a 标签
    aTags.forEach((link) => {
      if (link.href.startsWith('http') || link.href.startsWith('https')) {
        link.target = '_blank';
      }
    });
  })
}, {immediate: true})


const submitQuestion = (inputText) => {
  emit('submitQuestion', inputText);
}

const tipClick = (index) => {
  emit('tipClick', index)
}
const printedText = ref('');
const printedCard = ref(false);
const printText = (textToPrint) => {
  printedText.value = ''
  printedCard.value = false
  const printInterval = setInterval(() => {
    if (printedText.value.length < textToPrint.length) {
      printedText.value += textToPrint[printedText.value.length];
    } else {
      emit('resetSubmit')
      printedCard.value = true
      clearInterval(printInterval);
    }
    emit('resetScroll')
  }, 10); // 每0.5秒打印一个字符
}
let details = ref()
const printStreamText = async (textToPrint, printFlag) => {
  console.info(printFlag)
  console.info(textToPrint, 'textToPrint')
  if (printFlag == 'begin') { //开始打字
    printedCard.value = false
  } else if (printFlag == 'end') {
    printedCard.value = true
    printedText.value = await removeLastHash(printedText.value)
    details.value = await parseText(printedText.value)


    emit('addStreamToIndexDB', printedText.value)
    await parseText2(printedText.value)

    printedText.value = ""
  }
  printedText.value += textToPrint
  emit('resetScroll')


  console.info(printedText.value, 'printedText.value')
}

watch(() => printedText.value, () => {
  nextTick(() => {
    const aTags = document.querySelectorAll('a');

    // 遍历所有的 a 标签
    aTags.forEach((link) => {
      if (link.href.startsWith('http') || link.href.startsWith('https')) {
        link.target = '_blank';
      }
    });
  })

}, {immediate: true})

const renderedMarkdown = (content) => {
  return content
}


let jons1 = `根据用户提供的制度内容生成涉及地市、发布时间、涉及文件数。需满足以下要求：
1. 生成结果必须以 |JSON| 格式编排。
2.citys代表涉及到哪些地市（枚举值为：江苏十三地市、省公司、集团）
  files代表一共涉及几个文件
  times代表涉及的文件的年份、月份
输出（以下为示例，请勿直接使用）：
  |{"citys": ["扬州","泰州"], "times": "2023年7月、2024年、2025年3月","files":"3"}|`;

let json2 = `根据用户提供的制度内容生成对比情况。需满足以下要求：
1. 生成结果必须以 |JSON| 格式编排。
2.between代表制度在不同地市或者部门间的差别

输出（以下为示例，请勿直接使用）：
|{"between": "南京分公司强调新员工的一线炼金培养计划，注重导师制度和差异化激励政策，旨在提升新员工的融入感、归属感和获得感"}|`;

let jons3 = `根据用户提供的制度内容生成目标原文。需满足以下要求：
1. 生成结果必须以 |JSON| 格式编排。
2.original代表制度原文
3、filename代表制度文件名
4、chapter代表制度涉及章节
5、content代表制度内容
6、city代表来源涉及到哪些地市（枚举值为：江苏十三地市、省公司、集团）
7、department代表部门（集团客户部、市场经营部、财务部等）
8、time代表制度文件发布时间

输出（以下为示例，请勿直接使用）：
|{"original": [{
    "filename": "《中国移动通信集团江苏有限公司常州分公司ICT商机管理办法（2022年修订版）_1.docx》",
    "chapter": "商机奖惩体系",
    "content": "公司成立商机奖惩评审委员会，由集团客户部、财务部、人力资源部组成，同时设立专项奖励基金。集团客户部每月从ICT项目管理系统提取各区域录入商机清单，并结合省公司、市公司跟踪统计挂网商机情况、运营商中标情况汇总完成后报评审委员会审核，确定完成奖励和扣罚。本办法激励的有效商机指有预算、可参与、可跟进的项目，有前瞻性规划的重大项目。商机奖励适用全体公司员工（公司领导除外）。",
    "city": "常州",
    "department": "集团客户部",
    "time": "2022年"
}]}|`;


// 定义 parse_ai_response 函数
function parse_ai_response(response_text) {
  if (!response_text) {
    return null;
  }

  const parseStrategies = [
    (x) => JSON.parse(x), // 直接解析
    (x) => JSON.parse(x.split('|')[1].trim()), // 解析管道内的JSON
    (x) => JSON.parse(x.split("```json")[1].split("```")[0].trim()), // 解析代码块内的JSON
    (x) => JSON.parse(x.replace(/\n/g, '').replace(/\\/g, '').trim()) // 清理后解析
  ];

  for (const strategy of parseStrategies) {
    try {
      return strategy(response_text);
    } catch (error) {
      if (error instanceof SyntaxError || error instanceof TypeError) {
        continue;
      }
      throw error;
    }
  }

  return null;
}


const apiBaseUrl = import.meta.env.VITE_APP_ZUUL_PATH2; // 获取 代理地址 对应的值
const parseText = async (text) => {
  // 定义请求的 URL
  const url = `${apiBaseUrl}/completions`;

  // 创建请求配置的工厂函数
  const createRequestOptions = (prompt) => ({
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'AI-API-CODE': 'wif9hhnFEO',
      'AI-APP-KEY': 'VCRZouogAZ'
    },
    body: JSON.stringify({
      stream: false,
      model: 'qwen2.5_72B_nl',
      messages: [
        {role: 'system', content: prompt},
        {role: 'user', content: text}
      ]
    })
  });

  // 创建单个请求的处理函数
  const makeRequest = async (prompt) => {
    try {
      const response = await fetch(url, createRequestOptions(prompt));
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      return parse_ai_response(data.choices[0].message.content);
    } catch (error) {
      console.error('Fetch error:', error);
      return null;
    }
  };

  try {
    // 同时发起所有请求
    const [result1, result2] = await Promise.all([
      makeRequest(jons1),
      makeRequest(json2),
    ]);
    console.info('结果1 (涉及地市等信息):', result1);
    console.info('结果2 (对比情况):', result2);

    return {
      result1: result1,
      result2: result2,
    };
  } catch (error) {
    console.error('Error in parallel requests:', error);
  }
};
let loading3 = ref(false)
const parseText2 =async (text) => {
  loading3.value = true
  // 定义请求的 URL
  const url = `${apiBaseUrl}/completions`;
  // 定义请求的选项
  const options =
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'AI-API-CODE': 'wif9hhnFEO',
          'AI-APP-KEY': 'VCRZouogAZ'
        },
        body: JSON.stringify({
          stream: false,
          model: 'qwen2.5_72B_nl',
          messages: [
            {role: 'system', content: jons3},
            {role: 'user', content: text}
          ]
        })
      };



  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    details.value['result3'] = parse_ai_response(data.choices[0].message.content)
    console.info(details.value['result3'],'details.value[\'result3\']')
  } catch (error) {
    console.error('Fetch error:', error);
    return null;
  }
  finally {
    loading3.value = false
  }



  // // 发起请求
  // fetch(url, options).then(response => {
  //   if (!response.ok) {
  //     throw new Error(`HTTP error! status: ${response.status}`);
  //   }
  //   return response.json();
  // }).then(data => {
  //   console.info('结果3 (目标原文):', parse_ai_response(data.choices[0].message.content))
  //   details.value['result3'] = parse_ai_response(data.choices[0].message.content)
  // }).catch(error => {
  //   console.error('Fetch error:', error);
  // }).finally(() => {
  //   loading3.value = false
  // });


  // // 创建请求配置的工厂函数
  // const createRequestOptions = (prompt) => ({
  //   method: 'POST',
  //   headers: {
  //     'Content-Type': 'application/json;charset=UTF-8',
  //     'AI-API-CODE': 'wif9hhnFEO',
  //     'AI-APP-KEY': 'VCRZouogAZ'
  //   },
  //   body: JSON.stringify({
  //     stream: false,
  //     model: 'qwen2.5_72B_nl',
  //     messages: [
  //       {role: 'system', content: prompt},
  //       {role: 'user', content: text}
  //     ]
  //   })
  // });
  // fetch(url, createRequestOptions(jons3)).then()

  // try {
  //   const response = await fetch(url, createRequestOptions(prompt));
  //   if (!response.ok) {
  //     throw new Error(`HTTP error! status: ${response.status}`);
  //   }
  //   const data = await response.json();
  //   return parse_ai_response(data.choices[0].message.content);
  // } catch (error) {
  //   console.error('Fetch error:', error);
  //   return null;
  // }


  //
  // // 创建单个请求的处理函数
  // const makeRequest = async (prompt) => {
  //
  // };
  //
  // try {
  //   // 同时发起所有请求
  //   const [result3] = await Promise.all([
  //     makeRequest(jons3),
  //   ]);
  //
  //   return result3;
  // } catch (error) {
  //   console.error('Error in parallel requests:', error);
  // }
  // loading3.value = false
};


// 子组件默认包含是私有
defineExpose({
  printStreamText,
  printText,
  printedText
})

onMounted(async () => {

})
</script>

<style scoped lang="less">
.chat-content-wrap {
  .history-wrap {
    overflow: hidden;
    padding-bottom: 10px;


    .left-person {
      width: 100%;
      display: flex;
      //align-items: center;
      margin-bottom: 20px;

      .left-img {
        img {
          width: 36px;
          padding-top: 3px;
        }

      }

      .robot {
        position: relative;

        .robot-info {
          position: absolute;
          right: 10px;
          top: 10px;
        }
      }

      .right-info {
        margin-left: 8px;
        margin-top: 5px;

        .time {
          font-size: 12px;
          color: #bbbbbb;
        }

        .bubble {
          color: #414141;
          padding: 12px;
          border-radius: 0px 8px 8px 8px;
          background: #FFFFFF;
          box-shadow: 0px 0px 0px 0px rgba(171, 197, 232, 0.4);
          width: auto;
          max-width: calc(90vw - 80px);
          letter-spacing: 1px;
          text-align: justify;

          .title {
            font-size: 16px;
            line-height: 18px;
          }

          .title2 {
            line-height: 18px;

          }

          .button-icon {
            ::v-deep .el-button:hover {
              background-color: #74a1fd;
            }
          }

          .content-text {
            padding: 10px 20px;
            font-size: 14px;
            /*line-height: 20px;*/
            /*white-space: pre-line;*/
            word-break: break-all;
            word-wrap: break-word;

          }

          // 滚动条位置 --展示横向
          :deep(.__bar-is-vertical) {
            display: none !important;
          }

          // 隐藏横向滚动条
          :deep(.__bar-is-horizontal) {
            bottom: -1px !important;
          }

          .show-chat {
            display: flex;
            align-items: center; /* 垂直居中对齐 */

            .show-chat-tip {
              font-size: 14px;
              color: #666060;
              /* 添加动画 */
              animation: bounce 1.5s ease-in-out infinite;
              /* 利用变量动态计算动画延迟时间 */
              animation-delay: calc(.1s * var(--i));
            }
          }
        }


      }

    }

    .right-person {
      margin-bottom: 20px;
      width: 100%;
      overflow: hidden;

      .right-img {
        width: 58px;
        height: 60px;
        overflow: hidden;
        float: right;

        img {
          width: 48px;
        }
      }

      .wenzi {
        text-align: left;
        margin-right: 10px;
        display: block;
        float: right;

        .time {
          font-size: 12px;
          color: #000;
          text-align: right;
        }

        .bubble {
          padding: 10px 12px;
          margin-top: 6px;
          display: inline-block;
          min-width: 16px;
          float: right;
          background: #768EDF url("../../assets/image/aichat/sun.png") no-repeat left -120px top -50px;
          background-repeat: no-repeat;
          border-radius: 8px 0 8px 8px;
          word-break: break-all;
          max-width: calc(90vw - 125px);
          letter-spacing: 1px;
          color: #FFFFFF;

          .title {
            line-height: 18px;
            font-size: 14px;
          }
        }

        ::v-deep .bubble-full {
          max-width: calc(50vw - 125px);
        }
      }

    }

    .ai-reply {
      padding: 5px;
      padding-top: 10px;
      background-color: white;
      width: calc(100vw - 500px);
      position: relative;

      .text {
        color: #3F61A4;
      }

      .header-box {
        background: url("../../assets/image/aichat/replay-bg.png");
        padding: 7px 15px;
      }

      .right-img {
        position: absolute;
        top: 10px;
        right: 20px;
        height: 132px;
        width: 132px;
        background: url("../../assets/image/aichat/replay-icon.png") no-repeat 95% center;
        background-size: 132px 132px;
      }
    }

  }

  /* 美化整个滚动条 */

  ::-webkit-scrollbar {
    width: 8px; /* 设置滚动条的宽度 */
    background-color: #f9f9f9; /* 滚动条的背景色 */
  }

  /* 美化滚动条轨道 */

  ::-webkit-scrollbar-track {
    background: #FFFFFF; /* 轨道的背景色 */
  }

  /* 美化滚动条的滑块 */

  ::-webkit-scrollbar-thumb {
    background-color: #c1c1c1; /* 滑块的背景色 */
    border-radius: 10px; /* 滑块的圆角 */
    border: 2px solid #ffffff; /* 滑块边框 */
  }

  /* 当滑块悬停或活动时的样式 */

  ::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8; /* 悬停或活动状态下的背景色 */
  }

  ::v-deep .el-dialog {
    --el-dialog-margin-top: 10vh !important;
  }
}




</style>
<style lang="less">

.bg-F0F7FF {
  border-radius: 8px;
  background-color: #F0F7FF;

  .absolute {
    right: 0;
    top: 0;
    width: 68px;
    border-radius: 0px 8px 0px 17px;
  }
}

.no-chat {
  background: url("../../assets/image/aichat/tip-bg.png") no-repeat;
  background-size: 101% 100%;
  padding: 18px;
  margin: 25px;

  .text {
    /* 设置渐变背景 */
    background: linear-gradient(134.55175955168357deg, #53E8B9 0%, #48AFBC 24%, #4EA8BE 43%, #6CA7DB 68%, #78A4E8 83%, #6B77D6 100%); /* 将背景裁剪为文字的形状 */
    -webkit-background-clip: text;
    /* 文本颜色设置为透明，这样就会显示出背景的渐变效果 */
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    -moz-background-clip: text;
    -moz-text-fill-color: transparent;
    -ms-background-clip: text;
    -ms-text-fill-color: transparent;
    background-clip: text;
    text-fill-color: transparent;
  }

  .right-img {
    position: absolute;
    top: 30px;
    right: 50px;
    width: 254px;
    height: 225px;
    background: url("../../assets/image/aichat/tip-right.png") no-repeat;
    background-size: cover;
  }

  .tip-item {
    padding: 15px 11px;
    font-size: 16px;
    box-shadow: 0px 10px 12px 0px rgba(235, 240, 243, 0.39);
    border-radius: 8px;
    border: 1px solid #FFFFFF;
  }

  .item1 {
    background: #E3F4FF;
    color: #0066D4;
  }

  .item2 {
    background: #E7F3E9;
    color: #248124;
  }

  .item3 {
    background: #F0EEF6;
    color: #56368F;
  }

  .tip2-item {
    padding: 5px 14px;
    border-radius: 2px;
  }
}
.min-height{
  min-height: 200px;
}
</style>